import { reactive } from "vue";
import { formatMMSS } from "@/utils/format";

export const useAudio = (onEnded?: () => void) => {
  const audioCtx = new Audio();
  audioCtx.onplay = () => (audioData.paused = false);
  audioCtx.onpause = () => (audioData.paused = true);
  audioCtx.onended = () => {
    audioData.paused = true;
    audioData.percent = 0;
    audioData.currentTime = "00:00";
    onEnded?.();
  };
  audioCtx.ontimeupdate = () => {
    const percent = audioCtx.currentTime / audioCtx.duration;
    audioData.percent = Number.isNaN(percent) ? 0 : percent * 100;
    audioData.currentTime = formatMMSS(audioCtx.currentTime * 1000);
  };
  const audioPlayW = () => {
    audioData.paused = false;
    audioCtx.play();
  };
  const audioPlay = (src?: string) => {
    if (src) {
      if (audioCtx.src === src) {
        audioCtx.paused ? audioPlayW() : audioPause();
      } else {
        audioCtx.src = src;
        audioData.paused = false;
        audioData.percent = 0;
        audioCtx.play();
      }
    } else {
      if (audioCtx.src) {
        audioCtx.paused ? audioPlayW() : audioPause();
      }
    }
  };
  const audioPause = () => {
    audioData.paused = true;
    audioCtx.pause();
  };
  const audioSeek = (currentTime: number) => {
    audioCtx.currentTime = currentTime;
  };
  // const audioDestroy = () => {
  //   audioCtx.onplay = null;
  //   audioCtx.onpause = null;
  //   audioCtx.onended = null;
  //   audioCtx.ontimeupdate = null;
  // };

  const audioData = reactive({
    paused: true,
    currentTime: "00:00",
    percent: 0,
  });
  return { audioData, audioPlay, audioPause, audioSeek };
};
